package com.fenyin.samples.study.proxy;  

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;


/**
 *@Description:  被代理类接口实现类，动态代理的原理需要深入分析，明日分享
 *@Author:fengzhichao  
 *@Since:2012-8-25  
 *@Version:1.1.0
 */
public class MyProxyInterfaceImpl implements MyProxyInterface{
	private Object[] objs = new Object[1000];
	private int index=0;
	
	public void add(Object obj) {
		System.out.println("添加成功");
		objs[index++] = obj; 
		
	}
	
	public Object get() {
		System.out.println("获取成功");
		return objs[0]; 
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) throws InterruptedException{
		final MyProxyInterface target = new MyProxyInterfaceImpl();
		Thread.sleep(30*1000);
		System.out.println(target);
	    MyProxyInterface myProxy = (MyProxyInterface) Proxy.newProxyInstance(MyProxyInterface.class.getClassLoader(), new Class[]{MyProxyInterface.class}, new InvocationHandler(){

			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				System.out.println("方法被动态代理了....");
				return method.invoke(target, args);
			}
			
		});
	    for(int i=0;i<100;i++){
	    	myProxy.add("12345"+i);
//	    	每隔五秒添加数据
	    	Thread.sleep(5*1000);
	    }
		System.out.println(myProxy.get());
		Thread.sleep(10*60*1000);
		
//		final List list = new ArrayList();
//		List proxy = (List) Proxy.newProxyInstance(List.class.getClassLoader(), list.getClass().getInterfaces(), new InvocationHandler() {
//			
//			public Object invoke(Object proxy, Method method, Object[] args)
//					throws Throwable {
//				System.out.println("拦截方法");
//				return method.invoke(list, args);
//			}
//		});
//		proxy.add("test");
//		System.out.println(proxy.get(0));
		
	}

}